package dijjer.io.xfer.http;

import dijjer.AbstractFactory;
import dijjer.updater.*;
import dijjer.util.*;
import dijjer.util.logging.*;

import java.net.*;
import java.util.*;

public class HTTPServer extends AbstractThread {

	public static final String VERSION = "$Id: HTTPServer.java 37 2009-04-02 18:37:02Z mathias.demare $";
	public final static String CRLF = "\r\n";

	private final int _port;
	private boolean _continue = true;
	private static HTTPServer _HTTPServer;
	private final List _handlers = new ArrayList();

	public HTTPServer(int port) {
		_port = port;
	}

	protected boolean loop() throws InterruptedException {
		try {
			Socket sock = AbstractFactory.getFactory().getResourceManager().accept(_port);
			if (sock == null) {
				return false;
			}
			InetAddress addr = sock.getInetAddress();
			if (AbstractFactory.getFactory().getResourceManager().validAddress(addr.getHostName())) {
				Logger.debug("Accepting connection from: " + addr);
				HTTPRequestHandler handler = new HTTPRequestHandler(sock) {
					protected void cleanUp()
					{
						_handlers.remove(this);
					}
				};
				_handlers.add(handler);
				handler.startThread();
			} else {
				Logger.warning("Refused attempted web connection from " + addr);
				sock.close();
			}
		} catch (Exception ex) {
			Logger.error(ex);
			return false;
		}
		return _continue;
	}

	public static HTTPServer getHTTPServer()
	{
		return _HTTPServer;
	}

	public static void initServer(int localListenPort) throws Exception
	{
		_HTTPServer = new HTTPServer(localListenPort);
		_HTTPServer.startThread();
	}

	public String getURL()
	{
		return "http://localhost:" + _port;
	}

	protected void cleanUp()
	{
		List toRemove = (List) ((ArrayList)_handlers).clone();
		for (Iterator i = toRemove.iterator(); i.hasNext();) {
			HTTPRequestHandler httpRequestHandler = (HTTPRequestHandler) i.next();
			httpRequestHandler.shutdownThread();
		}
	}
}
